<script setup lang="ts">
import { ref, toRaw, onMounted } from "vue";
import { message, UploadChangeParam, UploadProps } from "ant-design-vue";
import {
  getCurrentUser,
  updateMyUser,
  listUserByPage,
  updateUser,
  userLogout,
} from "@/api/user";
import type { DescriptionsProps } from "ant-design-vue";
import type { User, UserQueryRequest, UserUpdateRequest } from "@/models/user";
import dayjs from "dayjs";
import {
  listDormitoryByPage,
  addDormitory,
  updateDormitory,
  deleteDormitory,
} from "@/api/dormitory";
import type {
  Dormitory,
  DormitoryQueryRequest,
  DormitoryAddRequest,
  DormitoryUpdateRequest,
} from "@/models/dormitory";
import DormitoryManagement from "@/components/DormitoryManagement.vue";
import BuildingManagement from "@/components/BuildingManagement.vue";
import EquipmentManagement from "@/components/EquipmentInfoManagement.vue";
import EquipmentDataManagement from "@/components/EquipmentDataManagement.vue";
import DormitoryExpenseBillManagement from "@/components/DormitoryExpenseBillManagement.vue";
import UserManagement from "@/components/UserManagement.vue";
import BalanceAlarmRecordManagement from "@/components/BalanceAlarmRecordManagement.vue";
import HistoryPayment from "@/components/PaymentBillManagement.vue";
import {
  UserOutlined,
  TeamOutlined,
  HomeOutlined,
  BuildingOutlined,
  DollarOutlined,
  NotificationOutlined,
  AccountBookOutlined,
  ToolOutlined,
  DatabaseOutlined,
  AlertOutlined,
} from "@ant-design/icons-vue";
import router from "@/router";
import { userLoginUserStore } from "@/store/userLoginUserStore";
import BalanceWarningManagement from "@/components/BalanceWarningManagement.vue";
import SystemNotificationManagement from "@/components/SystemNotificationManagement.vue";

// 模拟用户信息
const userInfo = ref({
  id: "1879338355388731393",
  userName: "曹跃跃",
  userAccount: "yupi",
  userPassword: "bfd8fd19b540e01a6aac5db69973d98a",
  userAvatar:
    "https://tse1-mm.cn.bing.net/th/id/OIP-C.qmIh5R-d_DmDKOYgzN09agHaJQ?rs=1&pid=ImgDetMain",
  userProfile: "第五人格玩家",
  userRole: "user",
  dormitoryId: 1,
  dormitoryVO: {
    dormitoryId: 1,
    dormitoryName: "201",
    buildingId: 1,
    createTime: "2025-01-15T07:52:49.000+00:00",
    updateTime: "2025-01-15T07:52:49.000+00:00",
    building: {
      buildingId: 1,
      buildingName: "Mo Lu",
      address: "941 Diplomacy Drive",
      createTime: "2006-05-10T23:25:44.000+00:00",
      updateTime: "2022-01-05T09:42:19.000+00:00",
    },
  },
});
//图片按钮
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (info.file.status == "done") {
    console.log("infochange");
    console.log(info.fileList[0].response.data);
    editForm.value.userAvatar = info.fileList[0].response.data;
    console.log("editForm.value.userAvatar" + editForm.value.userAvatar);
  } else if (info.file.status === "error") {
    message.error(`${info.file.name} file upload failed.`);
  }
};
const getUserInfo = async () => {
  const res = await getCurrentUser();
  userInfo.value = res.data.data;
  initEditForm();
};
getUserInfo();
// 编辑状态控制
const isEditing = ref(false);
const editForm = ref({
  id: "",
  userName: "",
  userAccount: "",
  userPassword: "",
  userAvatar: "",
  userProfile: "",
});
// 初始化编辑表单
const initEditForm = () => {
  editForm.value = {
    ...userInfo.value,
    userPassword: "",
  };
};

const fileList = ref<UploadProps["fileList"]>([]);
// 保存编辑
const handleSave = async () => {
  try {
    if (!editForm.value.userName) {
      message.error("请填写完整信息");
      return;
    }
    const rawEditForm = toRaw(editForm.value);
    const res = await updateMyUser(rawEditForm);
    if (res.data.code == 0 && res.data.data) {
      await getUserInfo();
      isEditing.value = false;
      message.success("个人信息更新成功！");
    } else {
      message.error("登录失败");
    }
  } catch (error) {
    message.error("更新失败");
  }
};

// 取消编辑
const handleCancel = () => {
  editForm.value = { ...userInfo.value };
  isEditing.value = false;
};

// 用户管理相关的数据和方法
const users = ref<User[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(6);
const searchText = ref("");
const loading = ref(false);

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  try {
    const userQueryRequest: UserQueryRequest = {
      current: currentPage.value,
      pageSize: pageSize.value,
      userName: searchText.value,
    };
    const res = await listUserByPage(userQueryRequest);
    if (res.data.code === 0) {
      users.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      message.error("获取用户列表失败");
    }
  } catch (error) {
    message.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索用户
const onSearch = () => {
  currentPage.value = 1;
  fetchUsers();
};

// 处理分页变化
const handleTableChange = (pagination: any) => {
  currentPage.value = pagination.current;
  pageSize.value = pagination.pageSize;
  fetchUsers();
};

// 初始加载
onMounted(() => {
  fetchUsers();
});

// 模拟水费数据
const waterBills = ref([
  {
    id: 1,
    dormitory: "A101",
    month: "2024-03",
    reading: 245.8,
    amount: 45.5,
    status: "已支付",
  },
  {
    id: 2,
    dormitory: "A102",
    month: "2024-03",
    reading: 198.3,
    amount: 38.2,
    status: "未支付",
  },
]);

// 模拟电费数据
const electricityBills = ref([
  {
    id: 1,
    dormitory: "A101",
    month: "2024-03",
    reading: 1334.8,
    amount: 78.2,
    status: "已支付",
  },
  {
    id: 2,
    dormitory: "A102",
    month: "2024-03",
    reading: 1156.2,
    amount: 65.4,
    status: "未支付",
  },
]);

// 模拟通知数据
const notifications = ref([
  {
    id: 1,
    title: "系统维护通知",
    content: "系统将于本周六进行例行维护",
    date: "2024-03-20",
    status: "已发布",
  },
  {
    id: 2,
    title: "缴费提醒",
    content: "请及时缴纳本月水电费",
    date: "2024-03-18",
    status: "已发布",
  },
]);

// 模拟删除操作
const handleDelete = (record: any) => {
  message.success("删除成功");
};

// 添加编辑用户的弹窗控制
const editModalVisible = ref(false);
const editingUser = ref<UserUpdateRequest>({
  id: "",
  userName: "",
  userAvatar: "",
  userProfile: "",
  userRole: "",
  dormitoryId: 0,
});

// 为编辑弹窗添加文件列表
const editFileList = ref<UploadProps["fileList"]>([]);

// 处理编辑用户的图片上传
const handleEditImageChange = (info: UploadChangeParam) => {
  if (info.file.status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (info.file.status == "done") {
    console.log("infochange");
    console.log(info.fileList[0].response.data);
    editingUser.value.userAvatar = info.fileList[0].response.data;
    console.log("editingUser.value.userAvatar" + editingUser.value.userAvatar);
  } else if (info.file.status === "error") {
    message.error(`${info.file.name} file upload failed.`);
  }
};

// 修改 handleEdit 函数
const handleEdit = (record: User) => {
  // 不复制密码字段
  const { userPassword, ...rest } = record;
  editingUser.value = {
    ...rest,
    userPassword: "", // 初始化为空字符串
  };
  editFileList.value = record.userAvatar
    ? [
        {
          uid: "-1",
          name: "avatar",
          status: "done",
          url: record.userAvatar,
        },
      ]
    : [];
  editModalVisible.value = true;
};

// 修改 handleEditSave 函数
const handleEditSave = async () => {
  try {
    const updateData = { ...editingUser.value };
    // 如果密码为空，则不传递密码字段
    if (!updateData.userPassword) {
      delete updateData.userPassword;
    }
    const res = await updateUser(updateData);
    if (res.data.code === 0) {
      message.success("更新成功");
      editModalVisible.value = false;
      fetchUsers();
    } else {
      message.error(res.data.message || "更新失败");
    }
  } catch (error) {
    message.error("更新失败");
  }
};
const loginUserStore = userLoginUserStore();
const selectedKeys = ref(["1"]);
const openKeys = ref(["sub1"]);

const handleLogout = async () => {
  try {
    const res = await userLogout();
    if (res.data.code === 0) {
      message.success("退出登录成功");
      // 清除本地存储的用户信息（如果有的话）
      loginUserStore.setLoginUser(null);
      // 跳转到登录页
      await router.push("/");
    } else {
      message.error(res.data.message || "退出失败");
    }
  } catch (error) {
    message.error("退出失败");
  }
};

const size = ref<DescriptionsProps["size"]>("default");
const onChange = (e: any) => {
  size.value = e.target.value;
};

// 添加用户相关方法
const handleAdd = () => {
  editModalVisible.value = true;
  editingUser.value = {
    id: "",
    userName: "",
    userAccount: "",
    userPassword: "",
    userAvatar: "",
    userProfile: "",
    userRole: "user",
    dormitoryId: 1,
    money: 0,
  };
  editFileList.value = [];
};
</script>

<template>
  <a-layout class="layout">
    <!-- 顶部导航栏 -->
    <a-layout-header class="header">
      <div class="logo">水电管理系统</div>
      <a-button type="link" @click="handleLogout">退出登录</a-button>
    </a-layout-header>

    <a-layout>
      <!-- 侧边菜单 -->
      <a-layout-sider width="200" style="background: #fff">
        <a-menu
          v-model:selectedKeys="selectedKeys"
          v-model:openKeys="openKeys"
          mode="inline"
          :style="{ height: '100%', borderRight: 0 }"
        >
          <a-menu-item key="1" @click="getUserInfo">
            <template #icon>
              <user-outlined />
            </template>
            个人信息管理
          </a-menu-item>

          <a-sub-menu key="sub2">
            <template #icon>
              <home-outlined />
            </template>
            <template #title>住宿管理</template>
            <a-menu-item key="2">
              <template #icon>
                <team-outlined />
              </template>
              用户信息管理
            </a-menu-item>

            <a-menu-item key="7">
              <template #icon>
                <home-outlined />
              </template>
              宿舍信息管理
            </a-menu-item>

            <a-menu-item key="8">
              <template #icon>
                <building-outlined />
              </template>
              楼栋信息管理
            </a-menu-item>
          </a-sub-menu>

          <a-sub-menu key="sub1">
            <template #icon>
              <tool-outlined />
            </template>
            <template #title>设备管理</template>
            <a-menu-item key="3">设备信息管理</a-menu-item>
            <a-menu-item key="4">设备数据管理</a-menu-item>
          </a-sub-menu>

          <a-sub-menu key="sub3">
            <template #icon>
              <dollar-outlined />
            </template>
            <template #title>账单信息管理</template>
            <a-menu-item key="9">宿舍水电支出</a-menu-item>
            <a-menu-item key="5">历史缴费</a-menu-item>
          </a-sub-menu>

          <a-sub-menu key="sub4">
            <template #icon>
              <alert-outlined />
            </template>
            <template #title>余额报警信息管理</template>
            <a-menu-item key="10">余额报警规则修改</a-menu-item>
            <a-menu-item key="11">余额报警记录管理</a-menu-item>
          </a-sub-menu>
          <a-menu-item key="6">
            <template #icon>
              <notification-outlined />
            </template>
            通知管理
          </a-menu-item>
        </a-menu>
      </a-layout-sider>

      <!-- 主要内容区域 -->
      <a-layout-content class="content">
        <!-- 个人信息管理 -->
        <a-card v-if="selectedKeys.includes('1')" title="个人信息">
          <template #extra>
            <a-space>
              <a-button
                v-if="!isEditing"
                type="primary"
                @click="isEditing = true"
              >
                编辑信息
              </a-button>
              <template v-else>
                <a-button type="primary" @click="handleSave">保存</a-button>
                <a-button @click="handleCancel">取消</a-button>
              </template>
            </a-space>
          </template>
          <a-radio-group v-model:value="size" @change="onChange">
            <a-radio value="default">默认</a-radio>
            <a-radio value="middle">中</a-radio>
            <a-radio value="small">小</a-radio>
          </a-radio-group>
          <br />
          <br />
          <div v-if="!isEditing">
            <a-descriptions bordered :size="size">
              <a-descriptions-item label="头像" :span="3">
                <a-image v-if="userInfo.userAvatar" :src="userInfo.userAvatar"
                :width="100" height: auto;/>
              </a-descriptions-item>
              <a-descriptions-item label="姓名">{{
                userInfo.userName
              }}</a-descriptions-item>
              <a-descriptions-item v-if="userInfo.dormitoryVO" label="宿舍号">{{
                userInfo.dormitoryVO.dormitoryName
              }}</a-descriptions-item>
              <a-descriptions-item label="角色">{{
                userInfo.userRole
              }}</a-descriptions-item>
              <a-descriptions-item label="账号">{{
                userInfo.userAccount
              }}</a-descriptions-item>
              <a-descriptions-item label="密码" :span="2">{{
                userInfo.userPassword
              }}</a-descriptions-item>
              <a-descriptions-item label="地址" :span="3">{{
                userInfo.dormitoryVO.building.address
              }}</a-descriptions-item>
              <a-descriptions-item label="简介" :span="3">{{
                userInfo.userProfile
              }}</a-descriptions-item>
            </a-descriptions>
          </div>
          <div v-else>
            <a-form :model="editForm" layout="vertical">
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="姓名" required>
                    <a-input v-model:value="editForm.userName" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="宿舍号" required>
                    <a-input
                      v-model:value="userInfo.dormitoryVO.dormitoryName"
                      disabled
                    />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="账号" required>
                    <a-input v-model:value="editForm.userAccount" />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="密码" required>
                    <a-input-password v-model:value="editForm.userPassword" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="24">
                  <a-form-item label="简介" required>
                    <a-input v-model:value="editForm.userProfile" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
            <br />
            <div>
              <a-upload
                v-model:file-list="fileList"
                action="
                    http://117.72.66.230:8101/api/file/uploadNew"
                list-type="picture"
                @change="handleChange"
              >
                <a-button>
                  <upload-outlined></upload-outlined>
                  upload
                </a-button>
              </a-upload>
            </div>
          </div>
        </a-card>

        <!-- 用户信息管理 -->
        <a-card v-if="selectedKeys.includes('2')" title="用户管理">
          <template #extra>
            <a-space>
              <a-input-search
                v-model:value="searchText"
                placeholder="搜索用户"
                style="width: 200px"
                @search="onSearch"
              />
              <a-button type="primary" @click="handleAdd">添加用户</a-button>
            </a-space>
          </template>

          <a-table
            :dataSource="users"
            :columns="[
              { title: '用户名', dataIndex: 'userName', key: 'userName' },
              { title: '账号', dataIndex: 'userAccount', key: 'userAccount' },
              { title: '角色', dataIndex: 'userRole', key: 'userRole' },
              { title: '宿舍号', dataIndex: 'dormitoryId', key: 'dormitoryId' },
              {
                title: '操作',
                key: 'action',
                width: 200,
                slots: { customRender: 'action' },
              },
            ]"
            :loading="loading"
            :pagination="{
              total: total,
              current: currentPage,
              pageSize: pageSize,
              showSizeChanger: true,
              showQuickJumper: true,
            }"
            @change="handleTableChange"
          >
            <template #action="{ record }">
              <a-space>
                <a @click="handleEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要删除这个用户吗？"
                  @confirm="handleDelete(record)"
                >
                  <a>删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>

          <!-- 编辑用户弹窗 -->
          <a-modal
            v-model:visible="editModalVisible"
            :title="editingUser.id ? '编辑用户' : '添加用户'"
            @ok="handleEditSave"
          >
            <a-form :model="editingUser" layout="vertical">
              <a-form-item label="用户名" required>
                <a-input v-model:value="editingUser.userName" />
              </a-form-item>
              <a-form-item label="账号" required>
                <a-input v-model:value="editingUser.userAccount" />
              </a-form-item>
              <a-form-item label="密码" :required="!editingUser.id">
                <a-input-password v-model:value="editingUser.userPassword" />
              </a-form-item>
              <a-form-item label="角色">
                <a-select v-model:value="editingUser.userRole">
                  <a-select-option value="user">普通用户</a-select-option>
                  <a-select-option value="admin">管理员</a-select-option>
                  <a-select-option value="ban">禁用</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="宿舍号">
                <a-input-number
                  v-model:value="editingUser.dormitoryId"
                  :min="1"
                  style="width: 100%"
                />
              </a-form-item>
            </a-form>
          </a-modal>
        </a-card>

        <!-- 通知管理 -->
        <system-notification-management v-if="selectedKeys.includes('6')" />
        <!-- 宿舍信息管理 -->
        <dormitory-management v-if="selectedKeys.includes('7')" />

        <!-- 楼栋信息管理 -->
        <building-management v-if="selectedKeys.includes('8')" />

        <!-- 设备信息管理 -->
        <equipment-management v-if="selectedKeys.includes('3')" />

        <!-- 设备数据管理 -->
        <equipment-data-management v-if="selectedKeys.includes('4')" />

        <!-- 宿舍水电支出管理 -->
        <dormitory-expense-bill-management v-if="selectedKeys.includes('9')" />

        <balance-warning-management v-if="selectedKeys.includes('10')" />
        <!-- 历史缴费 -->
        <history-payment v-if="selectedKeys.includes('5')" />
        <!-- 余额预警 -->
        <balance-alarm-record-management v-if="selectedKeys.includes('11')" />
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<style scoped>
.layout {
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo {
  color: #000;
  font-size: 18px;
  font-weight: bold;
}

.content {
  padding: 24px;
  background: #f0f2f5;
  min-height: 280px;
}

.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 500;
}

:deep(.ant-tag) {
  min-width: 60px;
  text-align: center;
}

:deep(.ant-modal-body) {
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style>
